<template>
  <view class="container">
    <view class="store-detail">
      <view class="flex-between">
        <view class="store-info">
          <view class="flex-y-center font-32 text-bold ellipsis">
            {{ storeInfo.canteen_name }}
          </view>
          <view class="store-time flex-between">
            <text class="time-tag">{{ storeInfo.open_date }}</text>
            <view class="flex-y-center font-24 c-8d" @click="callPhone(storeInfo.telphone)">
              <image
                :src="$util.img('image/erqi/mobile.png')"
                mode="widthFix"
                class="m-r-10"
                style="width: 40rpx"
              ></image>
              {{ storeInfo.telphone }}
            </view>
          </view>
        </view>
        <image :src="$util.img(storeInfo.canteen_image)" mode="aspectFill" class="store-image" lazy-load></image>
      </view>
      <view class="store-address" @click="goMap">
        <!-- <view class="flex-y-center m-r-20">
					<u-icon name="map" color="#8D93A5" size="14"></u-icon>
					<text class="distance">距您3.2km</text>
				</view> -->
        <text class="ellipsis" style="display: inline-block">{{ storeInfo.address }}</text>
      </view>
    </view>
    <view class="u-demo-block">
      <u-notice-bar
        :text="deliverScope"
        mode="link"
        color="#ff8f33"
        url="/otherpages/food/scopeDescription"
      ></u-notice-bar>
    </view>

    <view class="health rel">
      <view class="healthItem" @click="goTo('/otherpages/tea/index')">
        <image class="img" :src="$util.img('image/sanqi/food_4.png')" mode="aspectFill" />
        <text class="font-30 font-weight-6">U优茶咖</text>
        <!-- <text class="font-24 c-78">美味随心所定</text> -->
      </view>
      <view class="healthItem" @click="goTo('/otherpages/food/customDetail')">
        <image class="img" :src="$util.img('image/food_1.png')" mode="aspectFill" />
        <text class="font-30 font-weight-6">膳食定制</text>
        <!-- <text class="font-24 c-78">美味随心所定</text> -->
      </view>
      <view class="healthItem" @click="goTo('/otherpages/food/privateRef')">
        <image class="img" :src="$util.img('image/food_2.png')" mode="aspectFill" />
        <text class="font-30 font-weight-6">私厨预约</text>
        <!-- <text class="font-24 c-78">美餐专享烹饪</text> -->
      </view>
      <view class="healthItem" @click="goTo('/otherpages/food/business')">
        <image class="img" :src="$util.img('image/food_3.png')" mode="aspectFill" />
        <text class="font-30 font-weight-6">宴会宴请</text>
        <!-- <text class="font-24 c-78">盛宴私享包间</text> -->
      </view>
    </view>

    <!-- 商品分类模块 -->
    <view class="scrollContent rel">
      <view class="fill-base radius-34 abDeliver">
        <u-tabs
          :list="deliverList"
          lineWidth="0"
          @click="tabDeliverClick"
          :activeStyle="{
            color: '#fff',
            background: '#FF8F33',
            padding: '6rpx 20rpx',
            borderRadius: '50rpx',
            fontSize: '26rpx',
          }"
          :inactiveStyle="{
            color: '#606882',
            background: '#ffffff',
            padding: '6rpx 20rpx',
            borderRadius: '50rpx',
            fontSize: '26rpx',
          }"
          itemStyle="padding-right: 0;padding-left:0; "
        >
        </u-tabs>
      </view>
      <scroll-view :scroll-y="true" class="scroll-left">
        <view
          class="left-cate"
          :class="index == cateIndex ? 'active' : ''"
          v-for="(item, index) in cateList"
          :key="index"
          @click="changeCate(item, index)"
        >
          <text>{{ item.category_name }}</text>
        </view>
      </scroll-view>
      <scroll-view
        :scroll-y="true"
        id="myScrollView"
        class="scroll-right"
        :scroll-top="scrollTop"
        @scrolltolower="scrolltolower"
      >
        <view class="right-info">
          <view class="font-26 c-60 m-b-20">{{ cateList[cateIndex].category_name }}</view>
          <view class="goods-list" v-for="(goodsitem, goodsindex) in goodsList" :key="goodsindex">
            <view class="list-image" @click="goFoodDetail(goodsitem)">
              <image :src="goodsImg(goodsitem.goods_image)" mode="aspectFill" :lazy-load="true"></image>
            </view>
            <view class="list-info">
              <view class="font-30 text-bold ellipsis" @click="goFoodDetail(goodsitem)">{{
                goodsitem.goods_name
              }}</view>
              <view class="c-8d font-24 m-b-10 ellipsis" @click="goFoodDetail(goodsitem)">{{
                goodsitem.introduction
              }}</view>
              <view class="c-8d font-24" @click="goFoodDetail(goodsitem)">已售:{{ goodsitem.sale_num }}</view>
              <view class="flex-between">
                <view class="font-36 text-bold" @click="goFoodDetail(goodsitem)">
                  <text class="font-20">￥</text>
                  {{ goodsitem.price }}
                </view>
                <view class="list-gg rel" v-if="goodsitem.goods_spec_format" @click="goFoodDetail(goodsitem)">
                  选规格
                  <u-badge
                    type="warning "
                    max="99"
                    :value="goodsitem.num"
                    bgColor="#fcd188"
                    :absolute="true"
                    :offset="[-10, 0]"
                  ></u-badge>
                </view>
                <view class="list-gg-btn" v-else-if="goodsitem.num > 0">
                  <u-icon
                    name="minus-circle"
                    color="#00D075"
                    size="20"
                    @click="editCart(goodsitem, goodsindex, 'sub')"
                  ></u-icon>
                  <text>{{ goodsitem.num }}</text>
                  <u-icon
                    name="plus-circle-fill"
                    color="#00D075"
                    size="20"
                    @click="editCart(goodsitem, goodsindex, 'add')"
                  ></u-icon>
                </view>
                <view class="list-gg-btn" v-else @click.stop="addCart(goodsitem)">
                  <u-icon name="plus-circle-fill" color="#00D075" size="20"></u-icon>
                </view>
              </view>
            </view>
          </view>
          <emptyData
            :width="empty.width"
            :height="empty.height"
            :text="empty.text"
            :icon="empty.icon"
            :marginTop="empty.marginTop"
            v-if="goodsList.length == 0"
          ></emptyData>
        </view>
      </scroll-view>
    </view>

    <view class="fixfooter">
      <view class="start-price" v-if="parseFloat(storeInfo.start_price) > 0 && deliverIndex == 0"
        >起送价：{{ storeInfo.start_price }}元</view
      >
      <view class="flex-y-center">
        <view class="bag m-t-16" @click="showCart = true">
          <image :src="$util.img('image/bag.png')" mode=""></image>
          <view class="badgebox">
            <u-badge max="99" :value="totalCount" bgColor="#FF2323"></u-badge>
          </view>
        </view>
        <view>
          <view class="font-24 c-8d">共 {{ totalCount }} 件,需支付</view>
          <view class="font-36 text-bold c-origin m-r-4" style="line-height: 1"> ￥{{ totalPrice }} </view>
        </view>
      </view>
      <view class="submit m-t-14" @click="submit()" v-if="storeInfo.status == 1">下单</view>
      <view class="submit m-t-14" v-else style="background: #999">店铺休息</view>
    </view>

    <!-- 商品购物车组件 -->
    <cartGoods
      :show="showCart"
      v-if="showCart"
      @close="closeCart"
      :totalPrice="totalPrice"
      :totalCount="totalCount"
      :canteenId="storeInfo.canteen_id"
      @updateCart="getCartCount"
    ></cartGoods>
    <!-- 登录 -->
    <login-pop ref="loginDialog"></login-pop>
    <!-- 引入校验服务范围组件 -->
    <locationScope :show="showLocationScope" @close="closeLocationScope" v-if="showLocationScope"></locationScope>
  </view>
</template>

<script>
import locationScope from "../../components/locationScope/locationScope.vue";
import cartGoods from "../../components/cartGoods/cartGoods.vue";
export default {
  components: {
    cartGoods,
    locationScope,
  },
  data() {
    return {
      targetId: "", // 用于存储滚动目标视图的id
      storeInfo: {
        // 店铺信息
        canteen_id: 0,
      },
      cateIndex: 0,
      cateList: [],
      goodsPage: 1,
      goodsList: [],
      //购物车数据
      cartList: [],
      totalCount: 0,
      totalPrice: 0,
      showCart: false,
      empty: {
        width: 135,
        height: 134,
        text: "暂无数据",
        icon: "/image/emptyAddress.png",
        marginTop: 30,
      },
      scrollTop: 0,
      deliverScope: "",
      // 服务范围
      showLocationScope: false,
      deliverIndex: 0,
      deliverList: [
        {
          name: "配送",
        },
        {
          name: "自提",
        },
      ],
    };
  },
  onLoad() {
    if (!uni.getStorageSync("token")) this.$refs.loginDialog.open();

    uni.getLocation({
      type: "gcj02",
      success: (res) => {
        let obj = uni.getStorageSync("location");
        if (obj) {
          let a = this.$util.getDistance(obj.latitude, obj.longitude, res.latitude, res.longitude);
          if (a > 20) {
            uni.removeStorageSync("store");
          }
        }
        uni.setStorage({
          key: "location",
          data: {
            latitude: res.latitude,
            longitude: res.longitude,
          },
        });
      },
    });

    // if (uni.getStorageSync("location") && uni.getStorageSync("storeInfo")) {
    //   this.checkedLocationScope();
    // }
  },
  onShow() {
    // if(uni.getStorageSync('storeInfo')) {
    //   this.storeInfo = uni.getStorageSync('storeInfo')
    //   this.getStoreCategory()
    // }else {
    this.getStoreList();
    // }

    // 同步余额移动到下单页面
    // if(uni.getStorageSync('token')) {
    // 	this.updateBalance()
    // }

    // 获取配送范围说明
    this.getDeliverScope();
  },
  methods: {
    tabDeliverClick(e) {
      this.deliverIndex = e.index;
      if (this.deliverIndex == 0) {
        uni.setStorageSync("delivery", {
          title: "快递发货",
          name: "express",
        });
      } else {
        uni.setStorageSync("delivery", {
          title: "门店自提",
          name: "store",
        });
      }
    },
    checkedLocationScope() {
      let location = uni.getStorageSync("location");
      this.$api.sendRequest({
        url: "/canteen/api/ordercreate/verifyArea",
        data: {
          latitude: location.latitude,
          longitude: location.longitude,
          canteen_id: uni.getStorageSync("storeInfo").canteen_id || 0,
        },
        success: (res) => {
          if (res.code == 0) {
            this.showLocationScope = false;
          } else {
            this.showLocationScope = true;
          }
        },
      });
    },
    closeLocationScope() {
      this.showLocationScope = false;
    },
    goTo(url) {
      this.$util.redirectTo(url);
    },
    updateBalance() {
      this.$api.sendRequest({
        url: "/api/member/syncYinBaoBalance",
        data: {},
        success: (res) => {
          if (res.code == 0) {
            console.log("已同步");
          }
        },
      });
    },
    getDeliverScope() {
      this.$api.sendRequest({
        url: "/api/food/servicearea",
        data: {},
        success: (res) => {
          if (res.code == 0) {
            this.deliverScope = res.data.title;
          }
        },
      });
    },
    submit() {
      // 判断是否登录
      if (!uni.getStorageSync("token")) {
        this.$util.showToast({
          title: "请先登录",
        });
        return false;
      }
      // 判断购物车是否有商品
      if (this.totalCount < 1) {
        this.$util.showToast({
          title: "请选择商品",
        });
        return false;
      }

      // 判断是否满足起送价
      if (this.totalPrice < parseFloat(this.storeInfo.start_price) && this.deliverIndex == 0) {
        this.$util.showToast({
          title: "订单金额不能小于起送价",
        });
        return false;
      }

      // 循环购物车数据，生成新的数组包含sku_price_id和amount
      let cart_ids = [];
      this.cartList.forEach((v, k) => {
        // 循环商品规格价格
        cart_ids.push(v.cart_id);
      });

      uni.setStorage({
        key: "orderFoodCreateData",
        data: {
          cart_ids: cart_ids.toString(),
          canteen_id: this.storeInfo.canteen_id,
        },
        success: () => {
          this.$util.redirectTo("/otherpages/food/submitOrder");
        },
      });
    },
    goFoodDetail(item) {
      this.$util.redirectTo("/otherpages/food/detail?id=" + item.sku_id);
    },
    closeCart() {
      this.showCart = false;
    },
    goodsImg(imgStr) {
      let imgs = imgStr.split(",");
      return imgs[0] ? this.$util.img(imgs[0], { size: "mid" }) : "image/emptyAddress.png";
    },
    changeCate(item, index) {
      this.cateIndex = index;
      // this.targetId =  'category-' + item.id;
      this.goodsPage = 1;
      console.log("8888", this.scrollTop);
      // this.scrollTop = 0;
      this.getGoodsList();
    },
    editCart(item, index, type) {
      let amount = type == "add" ? item.num + 1 : item.num - 1;
      // 限购判断
      if (item.is_limit && amount > item.max_buy) {
        this.$util.showToast({
          title: "限购" + item.max_buy + "件",
        });
        return false;
      }

      if (amount > 0) {
        this.$api.sendRequest({
          url: "/canteen/api/cart/edit",
          data: {
            cart_id: item.cart_id,
            num: amount,
          },
          success: (res) => {
            if (res.code == 0) {
              // 修改商品列表购物车数量
              this.goodsList[index].num = amount;
              this.getCartCount();
            } else {
              this.$util.showToast({
                title: res.message,
              });
            }
          },
        });
      } else {
        this.deleCart(item, index);
      }
    },
    //加入购物车
    addCart(item) {
      // 判断是否登录
      if (!uni.getStorageSync("token")) {
        this.$util.showToast({
          title: "请先登录",
        });
        return false;
      }
      this.$api.sendRequest({
        url: "/canteen/api/cart/add",
        data: {
          sku_id: item.sku_id,
          num: 1,
          canteen_id: this.storeInfo.canteen_id,
        },
        success: (res) => {
          if (res.code == 0) {
            this.getCartCount();
            this.getCartList();
            this.$util.showToast({
              title: "加入购物车成功",
            });
          } else {
            this.$util.showToast({
              title: res.message,
            });
          }
        },
      });
    },
    //获取购物车数量
    getCartCount() {
      this.$api.sendRequest({
        url: "/canteen/api/cart/money",
        data: {
          canteen_id: this.storeInfo.canteen_id,
        },
        success: (res) => {
          if (res.code == 0) {
            this.totalCount = res.data.count;
            if (parseFloat(res.data.member_price) == 0) {
              this.totalPrice = res.data.price;
            } else {
              this.totalPrice = res.data.member_price;
            }
          }
        },
      });
    },
    //购物车列表
    getCartList() {
      this.$api.sendRequest({
        url: "/canteen/api/cart/goodsLists",
        data: {
          canteen_id: this.storeInfo.canteen_id,
        },
        success: (res) => {
          if (res.code == 0) {
            var arr = res.data;
            this.cartList = arr;
            this.goodsList.forEach((item, index) => {
              item.num = 0;
              item.cart_id = 0;
              arr.forEach((vv) => {
                if (item.sku_id == vv.sku_id) {
                  item.num += vv.num;
                  item.cart_id = vv.cart_id;
                  item.is_limit = vv.is_limit;
                  item.max_buy = vv.max_buy;
                }
              });
            });

            this.$forceUpdate();
          } else {
            this.$util.showToast({
              title: res.message,
            });
          }
        },
      });
    },
    getStoreList() {
      this.$api.sendRequest({
        url: "/api/canteen/page",
        data: {
          page: 1,
        },
        success: (res) => {
          if (res.code == 0) {
            if (res.data.list.length > 0) {
              this.storeInfo = res.data.list[0];
              uni.setStorageSync("storeInfo", this.storeInfo);
              this.getStoreCategory();
            }
          } else {
            this.$util.showToast({ title: res.message });
          }
        },
      });
    },
    getStoreCategory() {
      this.$api.sendRequest({
        url: "/canteen/api/goodscategory/tree",
        data: {
          canteen_id: this.storeInfo.canteen_id,
        },
        success: (res) => {
          if (res.code == 0) {
            this.cateList = res.data;
            this.getGoodsList();
          } else {
            this.$util.showToast({ title: res.message });
          }
        },
      });
    },
    getGoodsList() {
      this.$api.sendRequest({
        url: "/canteen/api/goodssku/page",
        data: {
          page: this.goodsPage,
          canteen_id: this.storeInfo.canteen_id,
          category_id: this.cateList[this.cateIndex].category_id,
        },
        success: (res) => {
          if (res.code == 0) {
            if (this.goodsPage == 1) this.goodsList = [];
            this.goodsList = this.goodsList.concat(res.data.list);

            if (uni.getStorageSync("token")) {
              this.getCartList();
              this.getCartCount();
            }
          } else {
            this.$util.showToast({ title: res.message });
          }
        },
      });
    },
    scrolltolower() {
      this.goodsPage++;
      this.getGoodsList();
    },
    goMap() {
      // 在地图显示该位置导航
      uni.openLocation({
        latitude: Number(this.storeInfo.latitude),
        longitude: Number(this.storeInfo.longitude),
        name: this.storeInfo.canteen_name,
        address: this.storeInfo.full_address + this.storeInfo.address,
      });
    },
    callPhone(phone) {
      uni.makePhoneCall({
        phoneNumber: phone,
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  height: 100vh;
  padding-bottom: 0 !important;
}
.store-detail {
  padding: 24rpx 24rpx 0;

  .store-image {
    width: 146rpx;
    height: 146rpx;
    border-radius: 14rpx;
  }

  .store-info {
    width: 68%;
    margin-right: 20rpx;

    .store-time {
      // margin-bottom: 10rpx;
      margin-top: 10rpx;

      .time-tag {
        display: inline-block;
        padding: 4rpx 12rpx;
        border-radius: 4rpx;
        font-size: 20rpx;
        color: #fff;
        background: $color-title2;
        border-radius: 10rpx;
      }
    }

    .store-tags {
      display: flex;
      align-items: center;
      margin-bottom: 14rpx;

      .discount-tag {
        display: flex;
        align-items: center;
        font-size: 20rpx;
        color: #ff5040;
        border: 1px solid #ff5040;
        margin-right: 20rpx;
        border-radius: 10rpx;
        padding-right: 10rpx;

        .discount-icon {
          display: inline-block;
          width: 32rpx;
          text-align: center;
          background: #ff5040;
          color: #fff;
          border-radius: 10rpx;
          margin-right: 10rpx;
        }
      }

      .price-tag {
        font-size: 20rpx;
        color: #ff5040;
        border-radius: 10rpx;
        background: #fff0ef;
        padding: 0 10rpx;

        .separator {
          margin: 0 8rpx;
          color: #ff5040;
        }
      }
    }
  }

  .store-address {
    display: flex;
    align-items: center;
    font-size: 24rpx;
    color: #898fa3;
    margin-bottom: 16rpx;

    .distance {
      color: #8d93a5;
      margin-left: 4rpx;
    }
    .store-daohang {
      width: 22rpx;
      height: 22rpx;
      margin-right: 10rpx;
    }
  }
}

.store-active {
  width: 100%;
  height: 212rpx;
  image {
    width: 100%;
    height: 100%;
  }
}

.scrollContent {
  display: flex;
  height: calc(100vh - 690rpx);
  background: #fff;

  .scroll-left {
    width: 170rpx;
    margin-right: 20rpx;
    background-color: #f8f9fa;

    .left-cate {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      color: #606882;
      font-size: 26rpx;
      padding: 20rpx 0;

      image {
        width: 75rpx;
        height: 75rpx;
        margin-bottom: 10rpx;
      }
    }

    .active {
      color: #1c274c;
      font-weight: bold;
      background-color: #fff !important;
    }
  }

  .scroll-right {
    width: calc(100% - 190rpx);
    padding: 30rpx 0;

    .goods-list {
      display: flex;
      align-items: center;
      padding-right: 30rpx;
      margin-bottom: 30rpx;

      .list-info {
        width: 60%;
      }

      .list-image {
        position: relative;
        width: 197rpx;
        height: 197rpx;
        border-radius: 20rpx;
        margin-right: 10rpx;
        image {
          width: 100%;
          height: 100%;
        }
        .label {
          position: absolute;
          top: 14rpx;
          left: 22rpx;
          width: 59rpx;
          height: 35rpx;
          line-height: 35rpx;
          text-align: center;
          border-radius: 10rpx;
          background-color: $color-title2;
          color: #fff;
          font-size: 20rpx;
        }
      }

      .list-gg {
        width: 85rpx;
        height: 43rpx;
        line-height: 43rpx;
        text-align: center;
        background-color: $color-title2;
        color: #fff;
        font-size: 22rpx;
        border-radius: 20rpx;
      }

      .list-gg-btn {
        display: flex;
        align-items: center;
        font-weight: 500;
        color: #1c274c;
        text {
          display: inline-block;
          width: 40rpx;
          text-align: center;
        }
      }
    }
  }
}

.fixfooter {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
  height: 142rpx;
  z-index: 99999;
  height: calc(142rpx + env(safe-area-inset-bottom) / 2);
  padding-bottom: calc(env(safe-area-inset-bottom) / 2);
  box-sizing: border-box;
  .bag {
    position: relative;
    margin-right: 40rpx;
    image {
      width: 56rpx;
      height: 65rpx;
    }
    .badgebox {
      position: absolute;
      top: -12rpx;
      right: -10rpx;
    }
  }
  .submit {
    width: 265rpx;
    height: 86rpx;
    line-height: 86rpx;
    text-align: center;
    background-color: $color-title2;
    color: #fff;
    border-radius: 60rpx;
  }
  .dis {
    background-color: #cfd0d4 !important;
  }
}

.health {
  display: flex;
  align-items: center;
  justify-content: space-around;
  margin: 0 24rpx 24rpx;
  .healthItem {
    width: 160rpx;
    height: 194rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    border-radius: 20rpx;
    image {
      width: 70rpx;
      height: 70rpx;
    }
  }
}
.start-price {
  position: absolute;
  top: -3rpx;
  left: 132rpx;
  font-size: 24rpx;
  color: $color-title2;
  font-weight: bold;
}

.abDeliver {
  position: absolute;
  top: 12rpx;
  right: 16rpx;
  z-index: 9;
}
</style>
